﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Threading;
using System.Xml;
using System.IO;

using KxzzEntity.GardenEntity;
using Kaixin001.Common;
using KxzzEntity.UsersEntity;
using Kaixin001.StringUtil;

namespace Kaixin001.Garden
{
    public class GardenHelper
    {
        #region 变量
        private Kaixin001Http kaixin001Http = null;
        #region Urls

        #region Garden

        private string houseFriendUrl = "http://www.kaixin001.com/house/mystay_dialog.php?verify=";
        private string gardenIndexUrl = "http://www.kaixin001.com/!house/garden/index.php";
        private string gardenDetailsUrl = "http://www.kaixin001.com/!house/!garden//getconf.php?verify={0}&fuid={1}&r={2}";
        private string seedListUrl = "http://www.kaixin001.com/house/garden/seedlist.php?verify={0}&r={1}";
        private string seedInfoUrl = "http://www.kaixin001.com/house/garden/seedinfo.php?verify={0}&seedid={1}&r={2}";
        private string waterUrl = "http://www.kaixin001.com/house/garden/water.php?verify={0}&seedid={1}&fuid={2}&farmnum={3}&r={4}";
        private string buySeedUrl = "http://www.kaixin001.com/house/garden/buyseed.php?verify={0}&num={1}&seedid={2}";
        private string getMySeedsUrl = "http://www.kaixin001.com/house/garden/myseedlist.php?verify={0}&page={1}&r={2}";
        private string farmSeedUrl = "http://www.kaixin001.com/house/garden/farmseed.php?verify={0}&seedid={1}&fuid={2}&farmnum={3}&r={4}";
        private string ploughUrl = "http://www.kaixin001.com/house/garden/plough.php?verify={0}&seedid={1}&fuid={2}&farmnum={3}&r={4}";
        private string getMyGranaryUrl = "http://www.kaixin001.com/house/garden/mygranary.php?verify={0}&r={1}";
        private string submitSettingUrl = "http://www.kaixin001.com/house/garden/setting_submit.php?verify={0}&vermin={1}&farm={2}&steal={3}&water={4}";
        private string havestUrl = "http://www.kaixin001.com/house/garden/havest.php?verify={0}&seedid={1}&fuid={2}&farmnum={3}&r={4}";
        private string sellFruitUrl = "http://www.kaixin001.com/house/garden/sellfruit.php?verify={0}&all={1}&seedid={2}&num={3}";
        private string antiVerminUrl = "http://www.kaixin001.com/house/garden/antivermin.php?verify={0}&seedid={1}&fuid={2}&farmnum={3}&r={4}";
        private string antiGrassUrl = "http://www.kaixin001.com/house/garden/antigrass.php";
        private string homeUrl = "http://www.kaixin001.com/home/";
        private string ginsengUrl = "http://www.kaixin001.com/house/garden/ginseng.php?verify={0}&r={1}";
        private string checkUrl = "http://www.kaixin001.com/house/check.php";
        private string myFruitInfoUrl = "http://www.kaixin001.com/house/garden//myfruitinfo.php?seedid={0}&verify={1}&r={2}";
        private string presentFruitUrl = "http://www.kaixin001.com/house/garden//presentfruit.php";
        private string friendAjaxUrl = "http://www.kaixin001.com/house/garden/friend_ajax.php";
        private string myGardenIndexUrl_wap = "http://wap.kaixin001.com/house/garden/?uid={0}&verify={1}";
        private string friendGardenIndexUrl_wap = "http://wap.kaixin001.com/house/garden/?verify={0}&fuid={1}&url=%2Fhouse%2Fgarden%2Ffriendlist.php%3Fverify%3D{0}";

        #endregion

        #region Ranch

        private string ranchIndexUrl = "http://www.kaixin001.com/!house/ranch/index.php";
        private string ranchDetailsUrl = "http://www.kaixin001.com/!house/!ranch//getconf.php?verify={0}&fuid={1}&r={2}";
        private string ranchHavestUrl = "http://www.kaixin001.com/house/ranch//havest.php";
        private string ranchFoodUrl = "http://www.kaixin001.com/house/ranch//food.php";
        private string ranchProductUrl = "http://www.kaixin001.com/house/ranch//product.php?r={0}&verify={1}&fuid={2}&animalsid={3}";
        private string ranchBuyAnimalUrl = "http://www.kaixin001.com/house/ranch//buyanimals.php";
        private string ranchWaterUrl = "http://www.kaixin001.com/house/ranch//water.php";
        private string ranchMHavestUrl = "http://www.kaixin001.com/house/ranch//mhavest.php?fuid={0}&animalsid={1}&verify={2}&r={3}";
        private string ranchBreedableUrl = "http://www.kaixin001.com/house/ranch//breedable.php?verify={0}&r={0}";
        private string ranchGetFriendToolUrl = "http://www.kaixin001.com/!house/!ranch//getfriendtools.php?bskey={0}&verify={1}&r={2}";
        private string ranchBreedUrl = "http://www.kaixin001.com/house/ranch//breed.php?fuid={0}&animalsid={1}&verify={2}";
        private string animalsListUrl = "http://www.kaixin001.com/house/ranch//animalslist.php?verify={0}&r={1}";
        private string animalInfoUrl = "http://www.kaixin001.com/!house/!ranch//animalsinfo.php?id={0}&verify={1}&r={2}";
        private string smartAUrl = "http://www.kaixin001.com/house/garden//smarta.php?ordernum={0}&verify={1}";
        private string antiQuestionUrl = "http://www.kaixin001.com/house/garden/smartq.php?verify={0}&r={1}";
        private string antiCheckUrl = "http://www.kaixin001.com/house/garden//smartc.php?verify={0}&fuid={1}&r={2}";
        private string newmsgUrl = "http://www.kaixin001.com/home/newmsg.php";
        private string ranchMygranaryUrl = "http://www.kaixin001.com/house/ranch//mygranary.php?verify={0}&r={1}";
        private string ranchFruitInfoUrl = "http://www.kaixin001.com/!house/!ranch//myfruitinfo.php?type={0}&id={1}&verify={2}&r={3}";
        private string ranchPresentFruitUrl = "http://www.kaixin001.com/!house/!ranch//presentfruit.php";

        #endregion

        #endregion
        #endregion

        #region 属性
        private string verifyCode = string.Empty;
        /// <summary>
        /// 进入花园Session参数
        /// </summary>
        public string VerifyCode
        {
            get
            {
                return verifyCode;
            }
        }

        Random ran;

        private string r = string.Empty;
        /// <summary>
        /// 时间随机数
        /// </summary>
        public string RandomValue
        {
            get
            {
                r = ran.NextDouble().ToString();

                if (r.Length < 18)
                {
                    r += ran.Next(100);
                }

                return r;
            }
        }

        private string ret = string.Empty;
        /// <summary>
        /// 结果
        /// </summary>
        public string Ret
        {
            get
            {
                return ret;
            }
            set
            {
                ret = value;
            }
        }
        #endregion

        public GardenHelper(Kaixin001Http kaixin001Http)
        {
            this.kaixin001Http = kaixin001Http;
            ran = new Random(DateTime.Now.Millisecond);
        }

        /// <summary>
        /// 获取花园好友
        /// </summary>
        /// <returns>fuid, name</returns>
        public Dictionary<string, string> GetGardenFriend()
        {
            string html = kaixin001Http.GetHtml(gardenIndexUrl);
            verifyCode = StringHelper.GetMidString(html, "g_verify = \"", "\";");

            html = kaixin001Http.GetHtml(houseFriendUrl + verifyCode);
            

            Dictionary<string, string> friends = new Dictionary<string, string>();

            try
            {
                string reg = "<div class=\"l\" style=\"width:8em;\"><a href=\"javascript:gotoUser(?<fuid>[^<]+);\" class=\"sl\">(?<name>[^<]+)</a></div>";
                Regex re = new Regex(reg);
                MatchCollection mc = re.Matches(html);
                foreach (Match match in mc)
                {
                    if (match.Success)
                    {
                        friends.Add(match.Groups["fuid"].Value.Replace("(", "").Replace(")", ""), match.Groups["name"].Value);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return friends;
        }

        /// <summary>
        /// 获取花园信息
        /// </summary>
        /// <returns></returns>
        public GardenEntity GetGardenDetails(string fuid)
        {
            string result = kaixin001Http.GetHtml(string.Format(gardenDetailsUrl,
                                                verifyCode,
                                                string.IsNullOrEmpty(fuid) ? "0" : fuid,
                                                RandomValue));
            GardenDetails(result);
            return new GardenEntity();
        }

        public void GardenDetails(string xml)
        {
            xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + xml;

            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml(xml);

                if(!File.Exists("D:\\1.xml"))
                {
                    File.Create("D:\\1.xml");
                }
                doc.Save("D:\\1.xml");
            }
            catch (Exception)
            {
                try
                {
                    string parten = "<setting>(.*?)</setting>";
                    xml = Regex.Replace(xml, parten, "<setting><water></water><vermin></vermin><steal></steal><farm></farm></setting>");
                    doc.LoadXml(xml);
                    doc.Save("D:\\1.xml");
                }
                catch (Exception ex)
                {
                    string ErrMsg = "读取花园数据失败．" + ex.Message;

                    if (xml.Contains("你不是她好友，没有权限查看此内容"))
                    {
                        ErrMsg = "1";
                    return;
                    }

                }
            }

            if (doc.DocumentElement != null)
            {
                if (doc.DocumentElement.SelectSingleNode("account") != null)
                {
                    GardenAccountEntity ff = LoadAccount(doc.DocumentElement.SelectSingleNode("account"));
                }

                if (doc.DocumentElement.SelectSingleNode("garden") != null)
                {
                    List<GardenEntity> dd = LoadGardenItems(doc.DocumentElement.SelectSingleNode("garden"));
                }

                if (doc.DocumentElement.SelectSingleNode("ret") != null)
                {
                    Ret = doc.DocumentElement.SelectSingleNode("ret").InnerText;
                }
            }
        }

        #region 给属性赋值相关方法

        private GardenAccountEntity LoadAccount(XmlNode node)
        {
            GardenAccountEntity account = new GardenAccountEntity();
            foreach (XmlNode item in node.ChildNodes)
            {
                switch (item.Name)
                {
                    case "rank":
                        account.Rank = item.InnerText;
                        break;
                    case "ranktip":
                        account.RankTip = item.InnerText;
                        break;
                    case "cash":
                        account.Cash = item.InnerText;
                        break;
                    case "logo50":
                        account.Logo50 = item.InnerText;
                        break;
                    case "name":
                        account.Name = item.InnerText;
                        break;
                    case "cashtip":
                        account.CashTip = item.InnerText;
                        break;
                    case "bkswf":
                        account.BkSwf = item.InnerText;
                        break;
                    case "bfirst":
                        account.BFirst = item.InnerText;
                        break;
                    case "tcharms":
                        account.TCharms = item.InnerText;
                        break;
                    case "careurl":
                        account.CareUrl = item.InnerText;
                        break;
                    case "flowerwomanurl":
                        account.FlowerWomanUrl = item.InnerText;
                        break;
                    case "beeurl":
                        account.BeeUrl = item.InnerText;
                        break;
                    case "setting":
                        LoadSetting(item,account);
                        break;
                    default:
                        break;
                }
            }

            return account;
        }

        private void LoadSetting(XmlNode node,GardenAccountEntity account)
        {

            foreach (XmlNode item in node.ChildNodes)
            {
                switch (item.Name)
                {
                    case "water":
                        account.Setting.Water = item.InnerText;
                        break;
                    case "vermin":
                        account.Setting.Vermin = item.InnerText;
                        break;
                    case "steal":
                        account.Setting.Steal = item.InnerText;
                        break;
                    case "farm":
                        account.Setting.Farm = item.InnerText;
                        break;
                    default:
                        break;
                }
            }
        }

        private List<GardenEntity> LoadGardenItems(XmlNode node)
        {
            List<GardenEntity> gardenItems = new List<GardenEntity>();

            foreach (XmlNode item in node.ChildNodes)
            {
                gardenItems.Add(LoadGardenItem(item));
            }

            return gardenItems;
        }

        /// <summary>
        /// 读取花园作物
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private GardenEntity LoadGardenItem(XmlNode node)
        {
            GardenEntity etItem = new GardenEntity();

            #region 读取XML节点
            foreach (XmlNode item in node.ChildNodes)
            {
                switch (item.Name)
                {
                    case "water":
                        int water = 0;
                        int.TryParse(item.InnerText, out water);
                        etItem.Water = water;
                        break;
                    case "farmnum":
                        etItem.FarmNum = item.InnerText;
                        break;
                    case "vermin":
                        int vermin = 0;
                        int.TryParse(item.InnerText, out vermin);
                        etItem.Vermin = vermin;
                        break;
                    case "cropsid":
                        etItem.CropsId = item.InnerText;
                        break;
                    case "fuid":
                        etItem.FUId = item.InnerText;
                        break;
                    case "status":
                        etItem.Status = item.InnerText;
                        break;
                    case "shared":
                        etItem.Shared = item.InnerText;
                        break;
                    case "pic":
                        etItem.Pic = item.InnerText;
                        break;
                    case "fruitpic":
                        etItem.FruitPic = item.InnerText;
                        break;
                    case "picwidth":
                        etItem.PicWidth = item.InnerText;
                        break;
                    case "picheight":
                        etItem.PicHeight = item.InnerText;
                        break;
                    case "cropsstatus":
                        etItem.CropsStatus = item.InnerText;
                        break;
                    case "grow":
                        etItem.Grow = item.InnerText;
                        break;
                    case "totalgrow":
                        etItem.TotalGrow = item.InnerText;
                        break;
                    case "fruitnum":
                        etItem.FruitNum = item.InnerText;
                        break;
                    case "seedid":
                        etItem.SeedId = item.InnerText;
                        break;
                    case "crops":
                        etItem.Crops = item.InnerText;
                        break;
                    case "farm":
                        etItem.Farm = item.InnerText;
                        break;
                    case "grass":
                        etItem.Grass = item.InnerText;
                        break;
                    default:
                        break;
                }
            }
            #endregion

            return etItem;
        }

        #endregion
    }
}
